<script setup lang="ts">
import { useAuthStore } from '@/stores/auth'
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppHeader from '@/components/layout/AppHeader.vue'
import LeftSidebar from '@/components/layout/LeftSidebar.vue'
import RightContent from '@/pages/home/RightContent.vue'
import PopupModal from '@/components/common/PopupModal.vue'
import { type HomeSection, HOME_SECTIONS } from '@/constants/HOME'

const auth = useAuthStore()
const router = useRouter()
const route = useRoute()

onMounted(async () => {
  // 确保用户状态是最新的，但不强制要求登录
  await auth.ensureUserState()
})

const currentSection = ref<HomeSection>((route.query.section as HomeSection) || HOME_SECTIONS.RANKING)

// 弹窗状态管理
const showPopup = ref(false)

// 检查是否需要显示弹窗（首次访问或者用户设置）
onMounted(() => {
  // 检查localStorage中是否有标记表示今天已经显示过弹窗
  const today = new Date().toDateString()
  const lastShown = localStorage.getItem('client_popup-last-shown')

  if (lastShown !== today) {
    // 延迟一点显示弹窗，让页面先加载完成
    setTimeout(() => {
      showPopup.value = true
      localStorage.setItem('client_popup-last-shown', today)
    }, 500)
  }
})

watch(() => route.query.section, (val) => {
  if (val && typeof val === 'string') {
    currentSection.value = val as HomeSection
  }
})
</script>

<template>
  <div class="layout">
    <AppHeader />

    <!-- 主要内容区域 - 无论是否登录都显示 -->
    <div class="main">
      <LeftSidebar v-model="currentSection" />
      <RightContent v-model="currentSection" />
    </div>

    <!-- 弹窗组件 -->
    <PopupModal v-model="showPopup" />
  </div>
</template>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
}
.main {
  flex: 1;
  display: flex;
  min-height: 0;
}

/* 移动端响应式设计 */
@media (max-width: 480px) {
  .layout {
    padding-bottom: 80px; /* 为底部导航留出空间 */
  }

  .main {
    /* 在手机端，侧边栏变成固定定位，所以主内容区域占满宽度 */
    display: block;
  }
}
</style>
